package org.jasig.cas.web.myctrl.controller;

import org.jasig.cas.util.Pair;
import org.jasig.cas.web.dao.UserDao;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created by catold on 16/4/20.
 */
@Controller
@RequestMapping(value = "user")
public class UserController {
    private UserDao userDao;
    private String ip;


    @RequestMapping(value = "", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody Object insertUser(@RequestParam String username, @RequestParam String password, @RequestParam String email, @RequestParam String credit) {
        String ip = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getRemoteAddr();
        Pair<String, Boolean> result;

        if (this.ip != null && !this.ip.equals("%") && !this.ip.equals(ip)) {
            result = new Pair<String, Boolean>("success", false);
        } else {
            result = new Pair<String, Boolean>("success", userDao.insert(username, password, email, credit));
        }

        return result;
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}
